<template>
  <view class="page-container">
    <!-- 购物车为空 -->
    <view class="empty-cart" v-if="cartList.length === 0">
      <image class="empty-image" src="/static/images/icons/empty-cart.png" mode="aspectFit"></image>
      <text class="empty-text">购物车还是空的</text>
      <button class="btn-primary go-shopping" @click="goShopping">去逛逛</button>
    </view>
    
    <!-- 购物车列表 -->
    <view class="cart-content" v-else>
      <!-- 商品列表 -->
      <view class="cart-list">
        <view 
          class="cart-item" 
          v-for="item in cartList" 
          :key="item.id"
        >
          <view class="checkbox" @click="toggleSelect(item)">
            <view :class="['checkbox-icon', {'checked': item.selected}]">
              <text v-if="item.selected" class="iconfont">✓</text>
            </view>
          </view>
          
          <view class="item-content" @click="goProductDetail(item.productId)">
            <image class="item-image" :src="item.image" mode="aspectFill"></image>
            <view class="item-info">
              <text class="item-name text-ellipsis-2">{{ item.name }}</text>
              <text class="item-spec text-ellipsis">{{ item.specificationName }}</text>
              <view class="item-price-wrapper">
                <text class="item-price">{{ item.price }}</text>
              </view>
            </view>
          </view>
          
          <view class="item-action">
            <view class="item-quantity">
              <QuantityStepper 
                :value="item.count" 
                :min="1" 
                :max="99"
                @change="updateQuantity(item, $event)"
              />
            </view>
            <view class="item-delete" @click="deleteItem(item)">
              <text class="iconfont">×</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部工具栏 -->
      <view class="cart-toolbar">
        <view class="select-all" @click="toggleSelectAll">
          <view :class="['checkbox-icon', {'checked': isAllSelected}]">
            <text v-if="isAllSelected" class="iconfont">✓</text>
          </view>
          <text class="select-all-text">全选</text>
        </view>
        
        <view class="total-info">
          <view class="total-price-wrapper">
            <text class="total-price-label">合计：</text>
            <text class="total-price">{{ totalPrice.toFixed(2) }}</text>
          </view>
          <text class="total-count">共{{ totalCount }}件商品</text>
        </view>
        
        <button 
          class="btn-primary checkout-btn" 
          :class="{'btn-disabled': selectedCount === 0}" 
          :disabled="selectedCount === 0"
          @click="checkout"
        >
          结算({{ selectedCount }})
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';
import QuantityStepper from '@/components/QuantityStepper.vue';
import { showModal, showToast, navigateTo, switchTab } from '@/utils/common.js';
import cartApi from '@/api/cart.js';
import '@/styles/pages/cart/cart.scss';

export default {
  components: {
    QuantityStepper
  },
  computed: {
    ...mapState('cart', ['cartList']),
    ...mapGetters('cart', [
      'selectedCartList',
      'selectedCount',
      'totalPrice',
      'isAllSelected'
    ]),
    ...mapGetters('user', ['isLoggedIn']),
    totalCount() {
      return this.cartList.reduce((total, item) => total + item.count, 0);
    }
  },
  onLoad() {
    this.loadCartData();
  },
  onShow() {
    this.loadCartData();
  },
  methods: {
    ...mapActions('cart', [
      'getCartList',
      'updateCartItem',
      'removeCartItem',
      'selectAll'
    ]),
    
    // 加载购物车数据
    async loadCartData() {
      if (this.isLoggedIn) {
        try {
          const cartData = await cartApi.getCartList();
          this.getCartList(cartData);
        } catch (error) {
          console.error('获取购物车数据失败', error);
        }
      }
    },
    
    // 切换选中状态
    async toggleSelect(item) {
      if (!this.isLoggedIn) {
        this.goLogin();
        return;
      }
      
      try {
        await cartApi.updateCartItem({
          id: item.id,
          selected: !item.selected
        });
        
        await this.updateCartItem({
          id: item.id,
          selected: !item.selected
        });
      } catch (error) {
        console.error('更新商品选中状态失败', error);
      }
    },
    
    // 全选/取消全选
    async toggleSelectAll() {
      if (!this.isLoggedIn) {
        this.goLogin();
        return;
      }
      
      try {
        await cartApi.selectAll(!this.isAllSelected);
        await this.selectAll(!this.isAllSelected);
      } catch (error) {
        console.error('全选/取消全选失败', error);
      }
    },
    
    // 更新数量
    async updateQuantity(item, count) {
      if (!this.isLoggedIn) {
        this.goLogin();
        return;
      }
      
      try {
        await cartApi.updateCartItem({
          id: item.id,
          count
        });
        
        await this.updateCartItem({
          id: item.id,
          count
        });
      } catch (error) {
        console.error('更新商品数量失败', error);
      }
    },
    
    // 删除商品
    async deleteItem(item) {
      if (!this.isLoggedIn) {
        this.goLogin();
        return;
      }
      
      const result = await showModal('确定要删除该商品吗？');
      if (result) {
        try {
          await cartApi.removeCartItem(item.id);
          await this.removeCartItem(item.id);
        } catch (error) {
          console.error('删除商品失败', error);
        }
      }
    },
    
    // 结算
    checkout() {
      if (!this.isLoggedIn) {
        this.goLogin();
        return;
      }
      
      if (this.selectedCount === 0) {
        showToast('请至少选择一件商品');
        return;
      }
      
      const cartIds = this.selectedCartList.map(item => item.id);
      navigateTo(`/pages/order/checkout?cartIds=${cartIds.join(',')}`);
    },
    
    // 跳转到商品详情
    goProductDetail(id) {
      navigateTo(`/pages/product/detail?id=${id}`);
    },
    
    // 跳转到首页
    goShopping() {
      switchTab('/pages/index/index');
    },
    
    // 跳转到登录页
    goLogin() {
      navigateTo('/pages/login/index');
    }
  }
};
</script> 